import { useCurrentNode } from '@/hooks/useCurrentNode';
import { TVariables } from '@/utils/graph';
import { useFormMode } from '@/components/base/Form/mode';
import { MciForm } from '@/components/base';
import { ElTransfer, TransferDataItem } from 'element-plus';
import './index.scss';
import { PropType } from 'vue';

export const VariableList = defineComponent({
  props: {
    data: {
      type: Array as PropType<TVariables[]>,
      default: () => []
    }
  },
  setup(props) {
    const currentNode = useCurrentNode();
    const variablesOpts = ref<TransferDataItem[]>([]);
    const result = ref<string[]>([]);
    const formMode = useFormMode();
    const isDisabled = !(formMode?.mode === 'edit');

    const chooseSave = (value) => {
      const resultJson = JSON.stringify(value);
      const payloadStr = {
        result_config: resultJson
      };
      currentNode.savePayload(payloadStr);
    };

    onMounted(() => {
      const list = props.data || [];
      variablesOpts.value = list
        .filter((item) => !!item.varName)
        .map((item: TVariables) => {
          return {
            key: item.varName,
            label: [item.varLabel || '', item.varName || ''].join(': ')
          };
        });
      // payload反显
      const payloadList = JSON.parse(currentNode.getNodeData()?.payload?.result_config || '[]');
      // 筛选返回值中存在父级变量中的数据
      const intersection = variablesOpts.value.filter((obj) => {
        return payloadList.some((item) => item.varName === obj.key);
      });
      result.value = intersection.map((item) => item.key);
      // 转换保存数据
      const changeIntersection = intersection.map((item: any) => {
        return {
          varName: item.key,
          varLabel: item.label || ''
        };
      });
      chooseSave(changeIntersection);
    });
    return () => (
      <div class="p-16 py-20">
        <MciForm disabled={isDisabled}>
          <ElTransfer
            v-model={result.value}
            filterable={true}
            target-order="push"
            class={'flex justify-between items-center VariableListTransfer'}
            style={{ '--el-transfer-panel-width': 'auto' }}
            titles={['变量列表', '输出变量列表']}
            data={variablesOpts.value}
            disabled={true}
            onChange={(selectedKeys) => {
              const selectedItems = selectedKeys
                .map((key) => {
                  return variablesOpts.value.find((item) => item.key === key);
                })
                .map((item: any) => {
                  return {
                    varName: item.key,
                    varLabel: item.label || ''
                  };
                });
              chooseSave(selectedItems);
            }}
          />
        </MciForm>
      </div>
    );
  }
});
